package dkbta.server.domain.analyzer;

import static java.lang.Math.min;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;

/*
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 */
import org.w3c.dom.Element;

import dkbta.server.util.query.PlanPair;
import dkbta.util.Pair;
import dkbta.util.data.StatInfo;
import dkbta.util.plan.subperunit.TaskParserUtil;


public class SimpleAnalyzer extends AbstractQueryAnalyzer {

	public SimpleAnalyzer(Element plan) {
		super(plan);
		// TODO Auto-generated constructor stub
	}

	@Override
	public Hashtable<String, PlanPair> makePlans(Vector<String> cuStubs, String xmlPlans) {
		int numOfUnits = cuStubs.size();
		String [] plansArr = new String[numOfUnits];
		for(int i = 0; i < numOfUnits; i++){
			plansArr[i] = xmlPlans;
		}
		Hashtable<String, PlanPair> plans; /*<stubId,<plan,result>>*/
		plans = addToMap(cuStubs, plansArr);
		return plans;
	}
	
	//@Override
	public Hashtable<String, PlanPair> makePlans2(Vector<String> cuStubs, String xmlPlans) {
		//makePlans();
		int numOfUnits = cuStubs.size();
		String [] plansArr = new String[numOfUnits];
		Hashtable<String, PlanPair> plans; /*<stubId,<plan,result>>*/
		if(numOfUnits == 1){
			plansArr[0] = xmlPlans;
		}
		else{
			ArrayList<StatInfo> statsInfo = TaskParserUtil.setUnitIDs(super.getStats(), numOfUnits);	 		 
			try{			 		       
				String [] stringOfIntervals = null;
				String oldInterval = null;
				String temp = null;
				String unitString = null;
				int unitIndx = 0;
				String strLine = xmlPlans.replaceAll(">", ">\n");
				String[] strLineArr = xmlPlans.replaceAll(">", ">\n").split("\n");
				for(int i = 0; i < numOfUnits; i++){
					plansArr[i] = "";
				}
				boolean isIntervals = false;
				for(int tt = 0; tt < strLineArr.length; tt++)   {
					strLine = strLineArr[tt];
					if(strLine.indexOf("<Stat name")>=0){
						break;
					}
					if(strLine.indexOf("</Patients>")>=0 && unitIndx>0){
						plansArr[unitIndx-1] = plansArr[unitIndx-1] + unitString;
						unitIndx = 0;
					}
					if(strLine.indexOf("id=")>=0 && strLine.indexOf("Unit")<0)/*abstraction*/{
						oldInterval = strLine.substring(strLine.indexOf("id=")+4, strLine.length() - 2);
						Pair<Integer, Integer>[] ids = TaskParserUtil.parsePatientIds(oldInterval);
						int numOfPatients = TaskParserUtil.getNumOfPatients(ids);
						stringOfIntervals = TaskParserUtil.parseIntervals(ids, numOfPatients, min(numOfPatients,numOfUnits));
						isIntervals = true;
					}
					if(strLine.indexOf("name=")>=0 && strLine.indexOf("inputTableName")<0){
						String abstrFrom = TaskParserUtil.getAbstractionNameFromString(strLine);
						unitIndx = TaskParserUtil.getUnitIDindxForAbstraction(abstrFrom, statsInfo);
						for(int i = 0; i < numOfUnits; i++){
							if(i==unitIndx-1){
								temp = strLine;
								unitString = TaskParserUtil.getRemoteCalcString(stringOfIntervals[i], TaskParserUtil.getStatInterval(abstrFrom, statsInfo), temp);
							}
							else{
								temp = strLine.substring(0, strLine.lastIndexOf('"')+1) + " sendToUnits=" + '"' + unitIndx + '"' + 
								strLine.substring(strLine.lastIndexOf('"')+1);
							}
							plansArr[i] = plansArr[i] + temp;
						}
					}
					else{
						for(int i = 0; i < numOfUnits; i++){
							if(isIntervals){
								temp = strLine.replaceFirst(oldInterval, stringOfIntervals[i]);
								plansArr[i] = plansArr[i] + temp;
							}
							else{
								plansArr[i] = plansArr[i] + strLine;
							}
						}
						isIntervals = false;
					}
				}
				for(int i = 0; i < statsInfo.size(); i++){
					StatInfo stat = statsInfo.get(i);
					int indx = stat.getUnitID() - 1;
					plansArr[indx] = plansArr[indx] + stat.toString();
				}
				for(int i = 0; i < numOfUnits; i++){
					plansArr[i] = plansArr[i] + "\n" + "\t</Statistical>";
					plansArr[i] = plansArr[i] + "\n" + "</Plan>";
				}
			}catch (Exception e){
				System.err.println("Error: " + e.getMessage());
				e.printStackTrace();
			}
		}
		//writePlansToFile(plansArr);
		plans = addToMap(cuStubs, plansArr);
		return plans;
	}

	private Hashtable<String, PlanPair> addToMap(Vector<String> cuStubs, String[] fouts) {
		Hashtable<String, PlanPair> plans = new Hashtable<String, PlanPair>();
		for(int i = 0; i < fouts.length; i++){
			plans.put(cuStubs.get(i), new PlanPair(fouts[i]));
		}
		return plans;
	}

}

//private void writePlansToFile(String[] fouts) {
//for(int i = 0; i < fouts.length; i++){
//	writePlanToFile(fouts[i], "./files/plans_test/TPlan_" + (i+1) + ".xml");
//}		
//}
//
//private void writePlanToFile(String xmlSource, String filename) {
//try {
//
//	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
//	factory.setValidating(false);			
//	ByteArrayInputStream stream = new ByteArrayInputStream(xmlSource.replaceAll(">", ">\n").getBytes());						
//	Element doc = factory.newDocumentBuilder().parse(stream).getDocumentElement();			
//	
//	Transformer tFormer = TransformerFactory.newInstance().newTransformer();
//	tFormer.setOutputProperty(OutputKeys.INDENT, "yes");
//	Source source = new DOMSource(doc);
//	Result dest = new StreamResult(new File(filename));
//	tFormer.transform(source,dest);						
//} catch (Exception e) {
//	// TODO Auto-generated catch block
//	e.printStackTrace();
//}
//
//}


